import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

// 处理头像URL路径
export function getAvatarUrl(avatarPath: string | null | undefined): string {
  // 调试日志
  console.log('getAvatarUrl input:', avatarPath, 'type:', typeof avatarPath)
  
  if (!avatarPath || avatarPath === '') {
    console.log('getAvatarUrl: 头像路径为空，返回空字符串')
    return ''
  }
  
  // 如果已经是完整的URL，直接返回
  if (avatarPath.startsWith('http://') || avatarPath.startsWith('https://')) {
    console.log('getAvatarUrl: 完整URL，直接返回:', avatarPath)
    return avatarPath
  }
  
  // 如果是以/开头的绝对路径，使用代理路径
  if (avatarPath.startsWith('/')) {
    // 使用 Next.js 代理路径，避免跨域问题
    const proxyPath = `/api/proxy${avatarPath}`
    console.log('getAvatarUrl: 绝对路径，使用代理路径:', proxyPath)
    return proxyPath
  }
  
  // 如果是相对路径，使用代理路径
  const proxyPath = `/api/proxy/uploads/avatars/${avatarPath}`
  console.log('getAvatarUrl: 相对路径，使用代理路径:', proxyPath)
  return proxyPath
}

// 日期格式化函数
export function formatDate(date: Date | string, format: 'relative' | 'short' | 'long' = 'relative'): string {
  const dateObj = typeof date === 'string' ? new Date(date) : date
  
  if (isNaN(dateObj.getTime())) {
    return '无效日期'
  }

  const now = new Date()
  const diffInMs = now.getTime() - dateObj.getTime()
  const diffInMinutes = Math.floor(diffInMs / (1000 * 60))
  const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60))
  const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24))

  switch (format) {
    case 'relative':
      if (diffInMinutes < 1) {
        return '刚刚'
      } else if (diffInMinutes < 60) {
        return `${diffInMinutes}分钟前`
      } else if (diffInHours < 24) {
        return `${diffInHours}小时前`
      } else if (diffInDays < 7) {
        return `${diffInDays}天前`
      } else if (diffInDays < 30) {
        const weeks = Math.floor(diffInDays / 7)
        return `${weeks}周前`
      } else if (diffInDays < 365) {
        const months = Math.floor(diffInDays / 30)
        return `${months}个月前`
      } else {
        const years = Math.floor(diffInDays / 365)
        return `${years}年前`
      }
    
    case 'short':
      return dateObj.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    
    case 'long':
      return dateObj.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    
    default:
      return dateObj.toLocaleDateString('zh-CN')
  }
}
